
<template>
  <div style="display: flex; gap: 80px;">
    <!-- <div style="width: 100px; height: 50px; ;"></div> -->
    <div id="echartsMain1" style="width: 600px; height: 600px; " />
    <div style="padding-top: 60px;">
      <el-form ref="formItem" :model="formItem" label-width="120px">
        <el-form-item label="审批节点名称" prop="approvalNode" :rules="{ required: true, message: '审批节点名称不能为空'}">
          <div style="width: 100%;">
            <el-input v-model="formItem.approvalNode" placeholder="请输入审批节点名称" clearable size="small" />
          </div>
        </el-form-item>
        <el-form-item label="审批角色" prop="approvalRoleId" :rules="{ required: true, message: '请选择审批角色'}">
          <div style="width: 100%;">
            <el-select v-model="formItem.approvalRoleId" filterable placeholder="请选择审批角色" clearable size="small" width="100%">
              <el-option
                v-for="sitem in $props.roleList"
                :key="sitem.value"
                :label="sitem.label"
                :value="sitem.value"
              />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item>
          <div class="footer-btn">
            <el-button type="primary" size="mini" :loading="savaLoading" @click="onSubmit">保存</el-button>
            <el-button type="danger" size="mini" :lading="deleteLoading" @click="deleteItem">删除</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>

</template>
<script>
import * as echarts from 'echarts'
import request from '@/utils/request'
export default {
  props: {
    roleList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      formItem: {},
      list: [],
      savaLoading: false,
      deleteLoading: false,
      loadingState: {}
    }
  },
  computed: {

  },
  created() {
    this.openFullScreen2()
  },

  mounted() {
    this.initEarcht('init')
  },

  methods: {
    openFullScreen2() {
      const loading = this.$loading({
        lock: true

      })
      this.loadingState = loading
      // setTimeout(() => {
      //   loading.close()
      // }, 2000)
    },
    onSubmit() {
      this.$refs['formItem'].validate((valid) => {
        if (valid) {
          const { list, formItem } = this
          const index = list.findIndex(item => item.id === formItem.id)
          list[index] = formItem
          this.request(list, 'update')
        }
      })
    },
    async request(params, type) {
      try {
        if (type === 'delete') {
          this.deleteLoading = true
        }
        if (type === 'update') {
          this.savaLoading = true
        }
        request({ url: 'system/approveConfig', method: 'post', data: params }).then(res => {
          if (res.code === 200) {
            this.savaLoading = false
            this.deleteLoading = false
            this.initEarcht(type === 'delete' ? 'init' : '')
            this.$emit('onSubmit')
            this.$message({
              message: '保存成功',
              type: 'success'
            })
          }
        })
      } catch (error) {
        this.$message({
          message: error,
          type: 'warning'
        })
      }
    },
    getRoundedRectPath(width, height, radius) {
      const r = Math.min(radius, width / 2, height / 2)
      const w = width
      const h = height
      return [
        `M ${r},0`,
        `H ${w - r}`,
        `A ${r},${r} 0 0 1 ${w},${r}`,
        `V ${h - r}`,
        `A ${r},${r} 0 0 1 ${w - r},${h}`,
        `H ${r}`,
        `A ${r},${r} 0 0 1 0,${h - r}`,
        `V ${r}`,
        `A ${r},${r} 0 0 1 ${r},0`,
        `Z`
      ].join(' ')
    },

    // 使用示例
    // const path = createRoundedRectPath(250, 120, 15);
    deleteItem() {
      const { list, formItem } = this
      const index = list.findIndex(item => item.id === formItem.id)
      list.splice(index, 1)
      this.request(list, 'delete')
    },
    async initEarcht(type) {
      const list = await this.getConfig()
      this.loadingState?.close()
      this.list = list
      if (type === 'init') {
        this.formItem = list[0]
      }
      const chart = echarts.init(document.getElementById('echartsMain1'))
      let count = 0
      let xValue = 0
      let isPre = false
      const roundedRectPath = 'M 20,0 H 100 A 20,20 0 0 1 120,20 V 20 A 20,20 0 0 1 100,40 H 20 A 20,20 0 0 1 0,20 V 20 A 20,20 0 0 1 20,0 Z'

      const echartData = list.reduce((pre, cur, index) => {
        isPre ? xValue-- : xValue++
        pre.push({
          name: cur.approvalNode,
          itemId: cur.id,
          x: (xValue) * 60,
          y: count * 50,
          symbol: 'path://' + this.getRoundedRectPath(100, 30, 10),
          symbolSize: [100, 30]

        })
        if ((index + 1) % 3 === 0) {
          count++
          isPre = !isPre
          xValue = isPre ? 4 : 0
        }
        return pre
      }, [])
      const links = this.createNode(echartData)
      const option = {
        tooltip: {},
        series: [
          {
            itemStyle: {
              color: '#fff', // 背景色白色
              borderColor: '#C0C4CC', // 边框黑色
              borderWidth: 1,
              lineJoin: 'round'
            },
            type: 'graph',
            layout: 'none', // 力导向布局，也可以用 'none' 自定义坐标
            roam: true,
            label: {
              show: true,
              textStyle: {
                fontSize: 12 // 节点文本字体大小
              }
            },
            // itemStyle: {
            //   color: '#C0C4CC' // 所有节点统一颜色
            // },
            select: {
              itemStyle: {
                color: '#d14a61' // 选中节点颜色
              }
            },
            force: {
              repulsion: 1000,
              edgeLength: [50, 100]
            },
            edgeSymbol: ['none', 'arrow'],
            symbolSize: 50,

            data: echartData,

            links: links,
            lineStyle: {
              color: '#aaa',
              opacity: 0.9,
              width: 2,
              curveness: 0
            }
          }
        ]
      }

      chart.setOption(option)
      chart.on('click', (params) => {
        // params 包含被点击的节点信息
        if (params.dataType === 'node') {
          this.formItem = { ...list[params.dataIndex] }
          console.log(this.formItem)
        }
      })
    },
    async getConfig() {
      const data = await request({ url: 'system/approveConfig/list', method: 'get' })
      // const l = data.data.map(item => ({ ...item, name: item.approvalNode + '1' }))
      return [...data.data]
    },
    createNode(nodes) {
      const links = []
      for (let i = 0; i < nodes.length - 1; i++) {
        links.push({
          source: nodes[i].name,
          target: nodes[i + 1].name
        })
      }
      return links
    }
  }
}
</script>
